package com.scuec.groupfive.Controller;

import com.scuec.groupfive.service.CommunityAnalysisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/community/analysis")
@CrossOrigin
public class CommunityAnalysisController {

    @Autowired
    private CommunityAnalysisService communityAnalysisService;

    @GetMapping
    public Map<String, Object> getCommunityAnalysis(
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {

        Map<String, Object> result = new HashMap<>();

        // 设置默认日期范围(最近30天)
        if (startDate == null || endDate == null) {
            endDate = LocalDate.now().toString();
            startDate = LocalDate.now().minusDays(30).toString();
        }

        // 1. 获取互动趋势数据(带日期参数)
        List<Map<String, Object>> trends = communityAnalysisService.getInteractionTrends(startDate, endDate);
        result.put("interactionTrends", trends);

        // 2. 获取并处理帖子类型分布数据(也添加日期过滤)
        List<Map<String, Object>> distributions = communityAnalysisService.getPostTypeDistributions(startDate, endDate);
        if (distributions != null && !distributions.isEmpty()) {
            int total = distributions.stream()
                    .mapToInt(item -> ((Number) item.get("count")).intValue())
                    .sum();

            distributions.forEach(item -> {
                double percentage = total > 0 ?
                        ((Number) item.get("count")).intValue() * 100.0 / total : 0;
                item.put("percentage", Math.round(percentage * 100) / 100.0);
            });
        }

        result.put("postTypeDistributions", distributions);
        return result;
    }
}